package com.hsylient.redis.init;

import cn.hutool.bloomfilter.BitSetBloomFilter;
import cn.hutool.bloomfilter.BloomFilterUtil;
import com.hsylient.common.entity.User;
import com.hsylient.redis.mapper.UserMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 这个类会在项目启动好了以后执行，这里直接将布隆过滤器初始化掉。
 */
@Slf4j
@Component
public class BloomFilterInit implements CommandLineRunner {

    public static final BitSetBloomFilter bloomFilter = BloomFilterUtil.createBitSet(10, 5, 1);

    @Resource
    private UserMapper userMapper;

    @Override
    public void run(String... args) {
        List<User> users = userMapper.selectFormDb();
        if (!users.isEmpty()) {
            users.forEach(item -> bloomFilter.add(Objects.toString(item.getId())));
        } else {
            log.info("[初始化布隆过滤器] 从数据库中查询到的数据源为空");
        }
        log.info("[初始化布隆过滤器] 布隆过滤器初始化完成....");
    }
}
